﻿using System.Net.Http;
using System.Text.Json;
using MeterReader.WPF.Models;

namespace MeterReader.WPF.Services
{
    public class HistoryService : IHistory
    {
		private readonly IDialogService _dialogService;

		public HistoryService(IDialogService dialogService)
		{
			_dialogService = dialogService;
		}

		public async Task<List<string>> GetMetersListAsync(string url)
        {
            using (HttpClient client = new())
            {
                try
                {
                    var response = await client.GetAsync(url);
                    var json = await response.Content.ReadAsStringAsync();
                    var names = JsonSerializer.Deserialize<List<string>>(json);
                    return names ?? new List<string>();
                }
                catch (Exception ex)
                {
					ShowMsgDialog(ex.Message);
					return new List<string>() { "falut" };
                }
            }
        }

        public async Task<List<PointsInfo>> SearchHistoryAsync(string url)
        {
            using (HttpClient client = new())
            {
                try
                {
                    var response = await client.GetAsync(url);
                    var json = await response.Content.ReadAsStringAsync();
                    var pointsInfoList = JsonSerializer.Deserialize<List<PointsInfo>>(json);
                    return pointsInfoList ?? new List<PointsInfo>();
                }
                catch (Exception ex)
                {
                    ShowMsgDialog(ex.Message);
					return new List<PointsInfo>();
                }
            }
        }

		private void ShowMsgDialog(string msg)
		{
			DialogParameters paras = new DialogParameters();
			paras.Add("fault", msg);
			_dialogService.ShowDialog("Message", paras);
		}
	}
}
